﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Text;
using PizzaMario.Domain.Entities;
using PizzaMario.Domain.Mapping;

namespace PizzaMario.Domain.Concrete
{
    public class Context : DbContext
    {
        static Context()
        {
            //Database.SetInitializer<Context>(null); // Existing database
            Database.SetInitializer(new CreateDatabaseIfNotExists<Context>()); // New database 
        }

        public DbSet<Pizza> Pizzas { get; set; }
        public DbSet<Topping> Toppings { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            try
            {
                // Attribute
                modelBuilder.Configurations.Add(new PizzaMap());
                modelBuilder.Configurations.Add(new ToppingMap());

                base.OnModelCreating(modelBuilder);
            }
            catch (Exception exception)
            {
#if DEBUG
                var errorMessages = new StringBuilder();

                errorMessages.AppendLine(exception.GetType().ToString());

                errorMessages.Append(exception.InnerException == null ? exception.Message : exception.InnerException.Message);

                System.Diagnostics.Debug.Fail(errorMessages.ToString());
#else
                throw;
#endif
            }
        }

        protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
        {
            //Inject the Context so it can be used when validation an entity
            //var myItems = new Dictionary<object, object> { { "Context", this } };
            if (items != null)
            {
                items.Add("Context", this);
            } else
            {
                items = new Dictionary<object, object> { { "Context", this } };
            }
            return base.ValidateEntity(entityEntry, items);
        }
    }
}
